Passed
Branchmaster (46cd5c)
by Plamen
01:27
created

table.js ➔ ... ➔ this.LoadEndCalback   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
var strAsc = String.fromCharCode(9650); //▲
2
var strDesc = String.fromCharCode(9660);//▼
3
var xmlhttp;
4
var d;
5
6
var table = new function () {
7
    this.rq = null;
8
    this.tail = [];
9
10
    this.ReloadData = function (tableId) {
11
        var request = {};
12
        this.BuildRequest(request, tableId);
13
        this.LoadData(tableId, request);
14
    };
15
16
    this.BuildRequest = function (request, crntTableId, skipPropertyArray) {
17
        this.rq = request;
18
        this.checkSkip = function (skipProperty) {
19
            var result = false;
20
            if (skipPropertyArray && Object.prototype
21
                    .toString.call(skipPropertyArray) === '[object Array]') {
22
                if (skipPropertyArray.indexOf(skipProperty) >= 0) {
23
                    result = true;
24
                }
25
            }
26
            return result;
27
        };
28
        this.getSort = function () {
29
            var table = document.getElementById(crntTableId);
30
            var thTags = table.getElementsByTagName("thead")[0]
31
                    .getElementsByTagName("th");
32
            for (var i = 0; i < thTags.length; i++) {
33
                if (thTags[i].getElementsByTagName("a")[0] && thTags[i]
34
                        .getElementsByTagName("a")[0].getElementsByTagName("span")
35
                        .length === 1
36
                        ) {
37
                    var order = thTags[i].getElementsByTagName("a")[0]
38
                            .getElementsByTagName("span")[0].innerHTML;
39
                    if (order.length === 1) {
40
                        this.rq.colNo = i;
41
                        this.rq.colOrd = (order === window.strDesc) ?
42
                                "desc" : "asc";
43
                    }
44
                }
45
            }
46
        };
47
        this.getFilter = function () {
48
            var r = this.getFilterFieldsByTbaleID(crntTableId);
49
            if (r.filter !== null) {
50
                this.rq.filter = r.filter;
51
            }
52
            if (r.filterBy !== null) {
53
                this.rq.filterBy = r.filterBy;
54
            }
55
        };
56
57
        /* Build request object */
58
        if (!this.checkSkip("sort")) {
59
            this.getSort();
60
        }
61
        if (!this.checkSkip("filter")) {
62
            this.getFilter();
63
        }
64
65
        this.rq.tableId = crntTableId;
66
        return this.rq;
67
    };
68
69
    this.RequestToUrl = function (rq) {
70
        var url = location.pathname + ".json" + location.search;
71
        if (typeof rq === "object") {
72
            var getUrlVarName = {
73
                colNo: "col", colOrd: "ord", filter: "filter",
74
                filterBy: "filter-by", pageNo: "pg", exportType: "export",
75
                tableId: "table-id"
76
            };
77
            var flagFirst = location.search.length < 1 ? true : false;
78
            for (var r in rq) {
79
                if (!rq.hasOwnProperty(r)) {
80
                    continue; // Skip keys from the prototype.
81
                }
82
                var clue = flagFirst === true ? "?" : "&";
83
                url += clue + getUrlVarName[r] + "=" + rq[r];
84
                flagFirst = false;
85
            }
86
        }
87
        return url;
88
    };
89
90
    this.Filter = function (field) {
91
        var crntTableId = this.FilterGetTableId(field);
92
        if (crntTableId !== null) {
93
            var request = {};
94
            var exRq = this.rq;
95
            this.BuildRequest(request, crntTableId);
96
            if (exRq === null ||
97
                request.filter !== exRq.filter ||
98
                request.filterBy !== exRq.filterBy
99
            ) {
100
                this.LoadData(crntTableId, request);
101
            }
102
        }
103
    };
104
105
    this.FilterGetTableId = function (field) {
106
        if (field.tagName.toLowerCase() !== "select") {
107
            return field.getAttribute("data-table-id");
108
        } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
109
            var f = field.parentNode.parentNode.getElementsByTagName("input")[0];
110
            return '' === f.value ? null : f.getAttribute("data-table-id");
111
        }
112
    };
113
114
    this.GoPage = function (lnk) {
115
        var request = {};
116
        var table = this.getParent(lnk, "table");
117
        var crntTableId = table.getAttribute("id");
118
        this.BuildRequest(request, crntTableId);
119
        //check & serve pagination jump links
120
        var jumpDir = lnk.innerHTML.trim().substr(0, 1);
121
        if (jumpDir === "+" || jumpDir === "-") {
122
            var current = table.querySelector("tfoot .paging .a").innerHTML;
123
            var jump = lnk.innerHTML.replace("K", "000").replace("M", "000000000");
124
            var jumpPage = (parseInt(current) + parseInt(jump));
125
            lnk.parentNode.setAttribute("data-page", jumpPage);
126
            lnk.style.transform = "none";
127
        }
128
        request.pageNo = lnk.parentNode.hasAttribute("data-page") ?
129
                lnk.parentNode.getAttribute("data-page") :
130
                lnk.innerHTML;
131
        this.LoadData(crntTableId, request);
132
        return false;
133
    };
134
135
    this.Export = function (lnk, eType) {
136
        var request = {};
137
        var crntTableId = this.getParent(lnk, "table").getAttribute("id");
138
        this.BuildRequest(request, crntTableId);
139
        request.exportType = ["CSV", "Excel"].indexOf(eType) >= 0 ? eType : "csv";
140
        window.open(this.RequestToUrl(request));
141
        return false;
142
    };
143
144
    this.Sort = function (colNo, lnk) {
145
        var request = {};
146
        var crntTableId = this.getParent(lnk, "table").getAttribute("id");
147
        this.BuildRequest(request, crntTableId);
148
        if (Math.round(colNo) === request.colNo) {
149
            request.colOrd = request.colOrd === "asc" ? "desc" : "asc";
150
        } else {
151
            request.colNo = Math.round(colNo);
152
            request.colOrd = "asc";
153
        }
154
        this.LoadData(crntTableId, request);
155
        /* Clear and add new sort arrow */
156
        var headSpans = this.getParent(lnk, "thead").getElementsByTagName("span");
157
        var length = headSpans.length;
158
        for (var i = 0; i < length; i++) {
159
            headSpans[i].innerHTML = "";
160
        }
161
        lnk.getElementsByTagName("span")[0].innerHTML = (request.colOrd === "desc" ? window.strDesc : window.strAsc);
162
    };
163
164
    this.DrawSection = function (tableContainer, dt, tSection) {
165
        var section = tSection === "tfoot" ? "tfoot" : "tbody";
166
        tSection = document.getElementById(tableContainer).
167
                getElementsByTagName(section)[0];
168
        this.clearSection(tSection);
169
        for (var i = 0; i < dt.length; i++) {
170
            var row = dt[i];
171
            var tRow = document.createElement("tr");
172
173
            this.DrawRow(row, tRow);
174
175
            tSection.appendChild(tRow);
176
            if (section === "tfoot") {
177
                this.footerProcessPaginationLinks(tSection);
178
            }
179
            this.AppendRowCalback(tableContainer);
180
        }
181
    };
182
183
    this.DrawRow = function(row, tRow){
184
        for(var cell in row){
185
            if ( ! row.hasOwnProperty(cell)) {
186
                continue; // Skip keys from the prototype.
187
            }
188
            var tCell = document.createElement("td");
189
            if(typeof row[cell] === "string" || typeof row[cell] === "number"){
190
                tCell.innerHTML = row[cell];
191
            } else if(typeof row[cell] === "object"){
192
                this.DrawCellFromObject(row, cell, tCell);
193
            }
194
            tRow.appendChild(tCell);
195
        }
196
    };
197
198
    this.DrawCellFromObject = function (row, cell, tCell) {
199
        for (var attr in row[cell]) {
200
            if (!row[cell].hasOwnProperty(attr)) {
201
                continue; // Skip keys from the prototype.
202
            }
203
            if (typeof row[cell][attr] === "string") {
204
                tCell.innerHTML = row[cell][attr];
205
            } else if (typeof row[cell][attr] === "object") {
206
                for (var v in row[cell][attr]) {
207
                    if (!row[cell][attr].hasOwnProperty(v)) {
208
                        continue; // Skip keys from the prototype.
209
            }
210
                    tCell.setAttribute(v, row[cell][attr][v]);
211
        }
212
            }
213
        }
214
    };
215
216
    this.footerProcessPaginationLinks = function (tSection) {
217
        var pLinks = tSection.querySelectorAll(".paging a");
218
        if (pLinks.length > 0) {
219
            for (var j = 0; j < pLinks.length; j++) {
220
                pLinks[j].setAttribute("href", "javascript:void(0);");
221
                pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
222
            }
223
        }
224
    };
225
226
    this.clearSection = function (tSection) {
227
        if (this.iePrior(9)) {
228
            if (tSection.firstChild) {
229
                while (tSection.firstChild) {
230
                    tSection.removeChild(tSection.firstChild);
231
                }
232
            }
233
        } else {
234
            tSection.innerHTML = "";
235
        }
236
    };
237
238
    this.SetTheTableColumnsHoverEffect = function (tableContainer) {
239
        if (this.iePrior(9)) {
240
            return;
241
        }
242
        var tContainer = document.getElementById(tableContainer);
243
        var tHcells = tContainer.rows[0].cells;
244
        for (var i = 0; i < tHcells.length; i++) {
245
            if (tHcells[i].firstChild.tagName === "A") {
246
                tHcells[i].firstChild.setAttribute("onmouseover", "table.ColumnHover('" + tableContainer + "'," + i + ");");
247
                tHcells[i].firstChild.setAttribute("onmouseout", "table.ColumnHover('" + tableContainer + "');");
248
            }
249
        }
250
        var pLinks = tContainer.querySelectorAll("tfoot .paging a");
251
        if (pLinks.length > 0) {
252
            for (var j = 0; j < pLinks.length; j++) {
253
                pLinks[j].setAttribute("href", "javascript:void(0);");
254
                pLinks[j].setAttribute("onclick", "return table.GoPage(this);");
255
            }
256
        }
257
    };
258
259
    this.ColumnHover = function (tableContainer, index) {
260
        if (this.iePrior(9)) {
261
            return;
262
        }
263
        var tRow = document.getElementById(tableContainer).rows;
264
        index = Math.round(index);
265
        for (var i = 0; i < (tRow.length - 1); i++) {
266
            if (index >= 0) {
267
                tRow[i].cells[index].setAttribute("lang", "col-hover");
268
            } else {
269
                for (var j = 0; j < tRow[i].cells.length; j++) {
270
                    if (tRow[i].cells[j].lang) {
271
                        tRow[i].cells[j].removeAttribute("lang");
272
                    }
273
                }
274
            }
275
        }
276
    };
277
278
    this.getFilterFieldsByTbaleID = function (tableID) {
279
        var fields = {filterBy: null, filter: null};
280
        var filterDiv = this.getFilterDivByTableIDOrNull(tableID);
281
        if (filterDiv !== null) {
282
            var selectObj = filterDiv.getElementsByTagName("select")[0];
283
            var textObj = filterDiv.getElementsByTagName("input")[0];
284
            fields.filterBy = (selectObj === null || selectObj.options[selectObj.selectedIndex].value === "all") ? null : selectObj.options[selectObj.selectedIndex].value;
285
            fields.filter = (textObj === null || textObj.value.length === 0) ? null : encodeURIComponent(textObj.value.trim());
286
        }
287
        return fields;
288
    };
289
290
    this.getFilterDivByTableIDOrNull = function (tableID) {
291
        var res = null;
292
        if (document.getElementById(tableID).parentNode.getElementsByTagName("div").length > 0) {
293
            for (var i = 0; i < document.getElementById(tableID).parentNode.getElementsByTagName("div").length; i++) {
294
                if (document.getElementById(tableID).parentNode.getElementsByTagName("div")[i].getAttribute("class") === "filter") {
295
                    return document.getElementById(tableID).parentNode.getElementsByTagName("div")[i];
296
                }
297
            }
298
299
        }
300
        return res;
301
    };
302
303
    this.LoadData = function (tableContainer, rq) {
304
        this.setVisability(tableContainer, false);
305
        if (window.XMLHttpRequest) {
306
            xmlhttp = new XMLHttpRequest();/* code for IE7+, Firefox, Chrome, Opera, Safari */
307
        } else { /** global: ActiveXObject */
308
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");/*code for IE6, IE5 */
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
309
        }
310
        for (var i = 0; i < this.tail.length; i++) {
311
            var ex_xmlhttp = this.tail.shift();
312
            ex_xmlhttp.abort();
313
        }
314
        xmlhttp.onreadystatechange = function () {
315
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
316
                d = JSON.parse(xmlhttp.responseText);
317
                table.DrawSection(tableContainer, d.body);
318
                table.DrawSection(tableContainer, d.footer, "tfoot");
319
                table.LoadEndCalback(tableContainer);
320
                table.setVisability(tableContainer, true);
321
                if (typeof rq === "object") {
322
                    table.ColumnHover(tableContainer, rq.colNo);
323
                }
324
            }
325
        };
326
        xmlhttp.open("GET", this.RequestToUrl(rq), true);
327
        xmlhttp.send();
328
        this.tail.push(xmlhttp); //put in tail to may later abort any previous
329
    };
330
331
    this.setVisability = function (tableContainer, rq) {
332
        var tbl = document.getElementById(tableContainer);
333
        if (rq === true) {
334
            tbl.style.filter = "none";
335
            tbl.style.opacity = "1";
336
            tbl.style.cursor = "auto";
337
        } else if (rq === false) {
338
            tbl.style.filter = "blur(1px)";
339
            tbl.style.opacity = "0.8";
340
            tbl.style.cursor = "wait";
341
        } else {
342
            console.log("table error in the rq value"); /*Shows error*/
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
343
        }
344
    };
345
346
    this.getParent = function (obj, objType) {
347
        while (obj && obj.tagName !== objType.toUpperCase()) {
348
            obj = obj.parentNode;
349
        }
350
        return obj;
351
    };
352
353
    this.init = function (tableId) {
354
        this.SetTheTableColumnsHoverEffect(tableId);
355
    };
356
357
    this.iePrior = function (v) {
358
        var rv = false;
359
        if (/** global: navigator */ navigator.appName === 'Microsoft Internet Explorer') {
0 ignored issues
show
Bug introduced by
The variable navigator seems to be never declared. If this is a global, consider adding a /** global: navigator */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
360
            var ua = navigator.userAgent;
361
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
362
            if (re.exec(ua) !== null) {
363
                rv = parseFloat(RegExp.$1);
364
            }
365
            rv = rv < v ? true : false;
366
        }
367
        return rv;
368
    };
369
    this.loadJS = function (src) {
370
        var s = document.createElement('script');
371
        s.src = src;
372
        document.getElementsByTagName('head')[0].appendChild(s);
373
    };
374
    this.loadCSS = function (src) {
375
        var s = document.createElement('link');
376
        s.href = src;
377
        s.rel = "stylesheet";
378
        document.getElementsByTagName('head')[0].appendChild(s);
379
    };
380
381
    this.LoadEndCalback = function (tableId) {
382
        if (tableId) {/*Allows override*/
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
383
        }
384
    };
385
    this.AppendRowCalback = function (tableId) {
386
        if (tableId) {/*Allows override*/
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
387
        }
388
    };
389
};
390
391
/** Moves custom created filter to the Table's filter
392
 * @param {string} filterId
393
 * @param {string} tableId
394
 * @param {boolean} delay - needed in case the table is istill not executed */
395
function moveSelectorToTheTableFilter(filterId, tableId, delay) {
396
    if (delay === true) {
397
        setTimeout(function () {
398
            var filterDiv = document.getElementById(tableId)
399
                    .getElementsByTagName("div")[0];
400
            filterDiv.appendChild(document.getElementById(filterId));
401
        }, 500);
402
    } else {
403
        var filterDiv = document.getElementById(tableId)
404
                .getElementsByTagName("div")[0];
405
        filterDiv.appendChild(document.getElementById(filterId));
406
    }
407
}
408
function changeListCustomFilter(selectObj) {
409
    var fId = selectObj.options[selectObj.selectedIndex].value;
410
    var hasValue = fId !== "{!--Empty--!}";
411
    var varName = selectObj.getAttribute("name");
412
    var varPos = (document.URL.indexOf(varName) - (hasValue ? 0 : 1));
413
    if (varPos > 0) {
414
        var url = document.URL.substring(0, varPos);
415
    } else {
416
        var separator = document.URL.indexOf("?") > 0 ? "&" : "?";
417
        url = document.URL + (hasValue ? separator : "");
418
    }
419
    var newUrl = url + (hasValue ? (varName + "=" + fId) : "");
420
    location.assign(newUrl);
421
}
422
423
424
function tablesLoadData() {
425
    var tables = document.getElementsByTagName("table");
426
    var envPrior9 = table.iePrior(9);
427
    for (var i = 0; i < tables.length; i++) {
428
        var isProcessable = envPrior9 ?
429
                typeof tables[i]["data-table"] !== 'undefined' :
430
                tables[i].hasAttribute("data-table");
431
        if (isProcessable && tables[i].getAttribute("data-table") === "js") {
432
            table.LoadData(tables[i].id);
433
            table.SetTheTableColumnsHoverEffect(tables[i].id);
434
        }
435
    }
436
    if (table.iePrior(10)) {
437
        table.loadJS("/add/helpers/table/add/json2.js");
438
    }
439
440
    /*if(table.iePrior(8)){ //can be used to add apropriate tables links modifications
441
     // loadCSS("/add/helpers/table/add/ie7-and-down.css");
442
     }*/
443
}
444
445
/*if(window.addEventListener){window.addEventListener('load',tablesLoadData,false);} else if(window.attachEvent){window.attachEvent('onload',tablesLoadData);}*/